var debug = true;
if (!(debug && window.console)) {
	window.console = {}
	console['log'] = function() { return; }
}

var VKPlayer;

var ROUTER;
var AppView;
var USER;
var PLAYER;
var DEQUE;

var DOWNLOADING; // Флаг занятости сети..
var dtID; // id таймаута на освобождение

function isDownloading() {
    return DOWNLOADING;
}

function downloadingOn(delay) {
    DOWNLOADING = true;
    clearTimeout(dtID);
    dtID = setTimeout(downloadingOff, delay || 5000);
}

function downloadingOff() {
    DOWNLOADING = false;
}

function html_entity_decode(str) {
    var ta = document.createElement("textarea");
    ta.innerHTML = str.replace(/</g, "&lt;").replace(/>/g, "&gt;");
    toReturn = ta.value;
    ta = null;
    return toReturn
}

function resizeFrame(params) {

    var params = params || {};
    params = _.defaults(params,
        {
            keepHeights : []
        }
    );

	var headerHeight = $('#header').height();
	var contentHeight = $(VKPlayer.Selectors.content).height();
	var sidebarHeight = $('#sidebar').height();
	var paddingHeight = 100;

    var heights = _.union([contentHeight, sidebarHeight],params.keepHeights);
	var height = _.max(heights) + headerHeight + paddingHeight;

	VK.callMethod("resizeWindow", 700, height);
}


/**
 * Получает список аудиозаписей юзверя
 * @param uid
 * @param album_id
 * @returns Deferred object
 */
function getAudio(uid, album_id) {
	var dfr = $.Deferred();
	VK.api('audio.get', {uid: uid, album_id: album_id}, function(data) {
		dfr.resolve(data.response);
	});
	return dfr;
}

function getAudioByIds(audios) {
	var dfr = $.Deferred();
	VK.api('audio.getById', {audios: audios.join(',')}, function(data) {
		dfr.resolve(data.response);
	});
	return dfr;
}

function getFriends(uid) {

	var dfr = $.Deferred();

	var fields = 'uid,first_name,last_name,nickname,screen_name,sex,'
		+ 'bdate,city,country, timezone, photo, photo_medium,'
		+ 'photo_big, has_mobile, rate, contacts, education, online';

	VK.api('friends.get', {uid: uid, fields: fields}, function(data) {
		if (data.response) {
			dfr.resolve(data.response);
		}
	});

	return dfr;
}

function getAlbums(uid) {
	var dfr = $.Deferred();
	VK.api('audio.getAlbums', {uid: uid}, function(data) {
		if (data.response) {
			dfr.resolve({
				count: _.first(data.response.splice(0, 1)),
				list: data.response
			});
		}
	});
	return dfr;
}

function getProfiles(uids) {
	var dfr = $.Deferred();
	var fields = 'uid,first_name,last_name,nickname,screen_name,sex,'
		+ 'bdate,city,country, timezone, photo, photo_medium,'
		+ 'photo_big, has_mobile, rate, contacts, education, online';
	VK.api('getProfiles', {uids: uids, fields: fields}, function(data) {
		if (data.response) {
			dfr.resolve(data.response);
		}
	});
	return dfr;
}

function addAudio(data) {
	var dfr = $.Deferred();
	var params = {
		aid: data.aid,
		oid: data.owner_id
	}

	VK.api('audio.add', params, function(data) {
		if (data) {
			dfr.resolve(data);
		}
	});

	return dfr;
}


function removeAudio(data) {
	var dfr = $.Deferred();
	var params = {
		aid: data.aid,
		oid: data.owner_id
	}

	VK.api('audio.delete', params, function(data) {
		if (data) {
			dfr.resolve(data);
		}
	});

	return dfr;
}

function restoreAudio(data) {
	var dfr = $.Deferred();
	var params = {
		aid: data.aid,
		oid: data.owner_id
	}

	VK.api('audio.restore', params, function(data) {
		if (data) {
			dfr.resolve(data);
		}
	});

	return dfr;
}

function setTrackLink(trackModel) {
	var track = trackModel.toJSON();
	delete(track.tracklist);
	var query = track.artist + ' ' + track.title;

	searchAudioTestMode({q: query})
		.done(function(data) {
			if (!_.isEmpty(data.list)) {
				var target_track = _.first(data.list);
				ajaxLinkTracks(trackModel, [track, target_track]);
				trackModel.set({ link_audio_id: target_track.owner_id + '_' + target_track.aid })
			} else {
				searchAudio({q: query})
				.done(function(data) {
					if (!_.isEmpty(data.list)) {
						var target_track = _.first(data.list);
						ajaxLinkTracks(trackModel, [track, target_track]);
						trackModel.set({ link_audio_id: target_track.owner_id + '_' + target_track.aid })
					} else {
						var owner_id = trackModel.get('owner_id');
					}
				});
			}
		});
}

function searchAudioTestMode(data) {

	var dfr = $.Deferred();

	var apps = [
        [327488, 525159, 'g5vuj9EWFO'],
        [2118012, 1882836,'xYsD1Dtsng'],
        [19730188, 1881945, 'rcj0HPk4Wk'],
        [85838504, 1887506, 'nTCyM7WEBo'],
        [9142393, 1891705, 'MlO3y0UXFV'],
        [86844124, 1891718, '8NgTW7tjWm'],
        [4824199, 1915951, 'pvHpN0V001'],
        [5573107, 1914989, 'CChij669jU'],

        [6240007, 1972474, 'DMXPeITyti'],
        [102802046, 1985438, 'sPZCZS5YxJ'],
        [102813567, 1985491, 'UjgLqfMPgc'],
        [102815638, 1985494, 'vI7EmQNdS9'],
        [102819736, 1985507, '3V0H9Y7zo9']

    ];

    var getApiData = function(){
        return apps[Math.floor(Math.random()*apps.length)];
    }

	var api = getApiData();
    var url = "http://api.vk.com/api.php";

	var md5template = api[0]+'api_id='+api[1]+'auto_complete=1callback=callbacknamecount=2format=jsonmethod=audio.searchq='+html_entity_decode(data.q)+'sort=2test_mode=1'+api[2];
    var md5hash = md5(md5template)

	var data = 'api_id='+api[1]+'&callback=callbackname&method=audio.search&format=json&sig='+md5hash+'&sort=2&auto_complete=1&test_mode=1&count=2&q='+encodeURIComponent(html_entity_decode(data.q))

	 $.ajax({
	  url: url,
	  data: data,
      dataType: 'jsonp',
      jsonp: 'callback',
      jsonpCallback: 'callbackname',
      cache:true
    })
    .success(function(data) {
		if (data.response) {
			dfr.resolve({
				count: _.first(data.response.splice(0, 1)),
				list: data.response
			});
		} else {
			dfr.resolve(data);
		}
    })

	return dfr;
}

function searchAudio(data) {

	var dfr = $.Deferred();
	var params = {
		q: html_entity_decode(data.q),
		sort: data.sort || 2,
		count: data.count || 1,
		auto_complete: data.auto_complete == null ? 1 : data.auto_complete
	}

	VK.api('audio.search', params, function(data) {
		if (data.response) {
			dfr.resolve({
				count: _.first(data.response.splice(0, 1)),
				list: data.response
			});
		} else {
			dfr.resolve(data);
		}
	});

	return dfr;
}

function searchVideo(data) {

	var dfr = $.Deferred();
	var params = {
		q: html_entity_decode(data.q),
		count: data.count || 10
	}

	VK.api('video.search', params, function(data) {
		if (data.response) {
			dfr.resolve({
				count: data.response.length,
				list: data.response
			});
		} else {
			dfr.resolve(data);
		}
	});

	return dfr;
}

function setFeedbackTrack(trackModel) {
	if (_.isEmpty(trackModel))
		return;

	var hash = trackModel.get('hash');
	var attitude = trackModel.get('attitude');
	$.ajax({
		url: '/feedback',
		type: 'POST',
		data: {hash: hash, attitude: attitude},
		dataType: 'json'
	})
	.success(function(data) {

	})
	.error(function(data) {
	});
}

function getMyFeedbacks(hashes) {
	var dfr = $.Deferred();
	$.ajax({
		url: '/get_feedbacks',
		type: 'POST',
		data: {hashes: hashes},
		dataType: 'json'
	})
		.success(function(data) {

			dfr.resolve(data.feedbacks);
		})
		.error(function(data) {
			dfr.resolve();
		});
	return dfr;
}

function setScrobbledTrack(trackModel) {
	if (_.isEmpty(trackModel))
		return;

	var hash = trackModel.get('hash');
	$.ajax({
		url: '/scrobble',
		type: 'POST',
		data: {hash: hash},
		dataType: 'json'
	})
		.success(function(data) {
		})
		.error(function(data) {

		});
}

function ajaxLinkTracks(trackModel, tracks) {
	if (!_.isArray(tracks))
		return false;

	$.ajax({
		url: '/link_tracks',
		type: 'POST',
		data: {tracks: tracks},
		dataType: 'json'
	})
		.success(function(data) {
			if (data.linking_success)
				trackModel.set({linked: true});
		})
		.error(function(data) {
		});
}

function renderTracklist(ids) {
	PLAYER.trigger('hide');
	var $content = $(VKPlayer.Selectors.content);
	$content.addClass('loading');

	if (! _.isEmpty(ids)) {
		getAudioByIds(ids)
			.done(function(result) {
				$content.removeClass('loading');
				if (_.isArray(result)) {
					var tracks = new VKPlayer.Collections.Tracks(result);
					tracklist = new VKPlayer.Models.Tracklist();
					tracklist.linkTracks(tracks);
					tracklist.trigger('show');
				} else {
					$content.html('Записей нет');
				}
			});
	}
	else {
		$content.removeClass('loading');
	}
}

jQuery.fn.clear = function() {
	PLAYER.trigger('hide');
    $(this).html('');
	return this;
}

jQuery.fn.appendTitle = function(data) {
	var params = _.extend({
		title: '',
		sub_title: ''
	}, data);
    var tpl = _.template($(VKPlayer.Templates.drawTitle).html());
    $(this).append(tpl(params));
	return this;
}

jQuery.fn.appendError = function(data) {
	var params = _.extend({
		title: 'Ошибка!',
		text: ''
	}, data);
    var tpl = _.template($(VKPlayer.Templates.drawError).html());
    $(this).append(tpl(params));
	return this;
}

function createPopup(popup_id) {
    var $popup = $('#'+popup_id);
    if (!$popup.length) {
        $popup = $('<div id="'+popup_id+'"></div>');
        return $popup.appendTo('body');
    } else {
        return $popup;
    }
}
function hidePopup($popup, delay) {
		if (delay) {
			var hide_id = $popup.data('hide_id');
			$popup
			.unbind().bind('mouseenter', function() {
				showPopup($popup.data('anchor'), 'mousemove', $popup.data('popup_type'), delay)
				//window.clearTimeout(hide_id);
			});

			var hide_id = window.setTimeout(function() {
				hidePopup($popup);
			}, delay);
			$popup.data('hide_id', hide_id);
		} else {
			$popup.trigger('hide.popup');
			$popup.hide().data('hide_id', '');
			if ($popup.data('popup_type') === 'center') $('body').removeClass('show-center-popup');
            resizeFrame();
		}
	}

	function showPopup(anchor, trigger, popup_type, delay_on_hide) {
		var trigger = trigger || 'click';
		if (trigger!=='click') trigger = 'mousemove'; //crunches
		var $anchor = $(anchor || this);
		var popup_id = $anchor.data('popup_id');
		if (!popup_id) return;

		var $popup = $('#' + popup_id);
		var $container = $('body');

		var hide_id = $popup.data('hide_id');
		if (hide_id) {
			window.clearTimeout(hide_id);
			$popup.data('hide_id', 0);
		}

		if (!$popup.is(':visible') || hide_id) { //если попап еще скрыт или собирается
			$container.bind(trigger + '.popup', function(e) { // при клике на боди скрыть попап
				// если кликнули в попап, и не в .close - не скрывать
				if ( $(e.target).closest($popup.add($anchor)).length && !$(e.target).is('.close,.close-popup')) return;
				hidePopup($popup, delay_on_hide);
				$container.unbind(e); //trigger+'.popup'
			});
		};

		if (popup_type) $popup.data('popup_type', popup_type);
		$popup.data('anchor', anchor);

		if(popup_type == 'absolute') {
			$container.append($popup);
		}

		if (!popup_type || popup_type == 'absolute') { // по умолчанию попап рисуем под якорем
			var position = $anchor.position();
			var offset = $anchor.offset();
			if (popup_type == 'absolute') position = offset;
			position.top += $anchor.outerHeight()-1;
			if (offset.left + $popup.outerWidth() > $container.outerWidth()) {
				position.left = '';
				position.right = 0;
			} else {
				position.right = '';
			}
			if ($popup.outerHeight() > $container.outerHeight()) {
				position.top = 0;
			} else if (offset.top + $popup.outerHeight() > $container.outerHeight()){
				position.top = '';
				position.bottom = 0;
			} else {
				position.bottom = '';
			}
		} else if(popup_type == 'horizontal') {
			$container.append($popup);
//			var pos = $anchor.position();
			var offset = $anchor.offset();
			var anchorWidth = $anchor.outerWidth();
			var windowWidth = $(window).width();

			var dir = offset.left + anchorWidth/2 < windowWidth/2 ;
			//0 == left, 1 == right: popup drawing from anchor
			var position = {top: offset.top + $anchor.height()/2 - 26 } //- $popup.height()/2
			if (dir) {
				$popup.addClass('right-type')
				position.left = offset.left + anchorWidth;
				position.right = '';
			} else {
				$popup.removeClass('right-type')
				position.left = '';
				position.right =  windowWidth - offset.left;
			}
		} else if(popup_type == 'center') {
			var marginTop =  $popup.data('marginTop') || 0;
            $popup.css('marginTop',marginTop);
			$container.addClass('show-center-popup').append($popup);
		}

		if (position)
			$popup.css(position);

		resizeFrame({keepHeights:[marginTop+$popup.height()]});
		return $popup.show();
	}

jQuery.fn.margin = function() {
var marginTop = this.outerHeight(true) - this.outerHeight();
var marginLeft = this.outerWidth(true) - this.outerWidth();

return {
    top: marginTop,
    left: marginLeft
}};

